import { Button, Card, Checkbox, Empty, List, Row, Space } from 'antd'
import React, { useMemo } from 'react'

const PhotoListSelect = function(props) {

  const {
    photos, checkedPhotos, onChangeCheckPhotos,
    renderCardDetail,
    imgSrcProp = 'src',
    pid = 'id',
    cols = 4
  } = props

  const originRenderDetail = (item, idx) => {
    return <Row justify={'end'}>
      <Space>
        <span>照片:{idx}</span>
        {getCheckbox(item)}
      </Space>
    </Row>
  }

  const indeterminate = useMemo(() =>
    checkedPhotos.length && photos.length !== checkedPhotos.length, [photos, checkedPhotos])

  const checkAll = useMemo(() => {
    return photos.length === checkedPhotos.length
  }, [photos, checkedPhotos])

  const getAllPhotoIds = () => photos.map(p => p[pid])

  const handleAllCheckChange = (flag) => void onChangeCheckPhotos(flag ? getAllPhotoIds() : Array.of())

  const getCheckbox = (item) => {
    return <Checkbox
      style={{ position: 'absolute', bottom: 5, right: 5 }}
      value={item[pid]}/>
  }

  const handleReverseAll = () => getAllPhotoIds()
    .filter(id => !checkedPhotos.includes(id)) |>onChangeCheckPhotos

  return <div>
    {
      do {
        if (!photos.length) {
          <Empty/>
        } else {
          <div>
            <Row justify={'end'}>
              <Space>
                <Button onClick={handleReverseAll} size={'small'} type={'link'}>反选</Button>
                <Checkbox
                  checked={checkAll}
                  indeterminate={indeterminate}
                  onChange={e => handleAllCheckChange(e.target.checked)}
                />
              </Space>
            </Row>
            <Checkbox.Group style={{ width: '100%' }}
                            onChange={(photoIds) => onChangeCheckPhotos(photoIds)}
                            value={checkedPhotos}>
              <List
                grid={{ gutter: 16, column: cols }}
                dataSource={photos}
                renderItem={(item, idx) => {
                  const { [imgSrcProp]: src } = item
                  return <List.Item>
                    <Card
                      hoverable
                      cover={<img draggable={false} style={{ height: 160 }} alt={src} src={src}/>}
                    >
                      {renderCardDetail ? renderCardDetail(item, { Checkbox: getCheckbox(item) }) : originRenderDetail(item, idx)}
                    </Card>
                  </List.Item>
                }}
              />
            </Checkbox.Group>
          </div>
        }
      }
    }
  </div>

}

export default PhotoListSelect
